
    /**  
    * @Title: WSGatewayServiceImpl.java
    * @Package com.efast.cafe.commponent.es.webservice.impl
    * @Description: TODO(用一句话描述该文件做什么)
    * @author Administrator
    * @date 2018年9月18日
    * @version V1.0  
    */
    
package com.efast.cafe.commponent.es.webservice.impl;


import javax.jws.WebService;
import javax.xml.bind.JAXBException;
import org.json.JSONObject;
import org.json.XML;
import org.slf4j.MDC;
import org.slf4j.event.Level;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Element;
import com.cafeauto.ws.Message;
import com.efast.cafe.commponent.es.common.entity.CommonEsConfig;
import com.efast.cafe.commponent.es.common.enums.ServiceTypeEnum;
import com.efast.cafe.commponent.es.common.service.CommonEsConfigService;
import com.efast.cafe.commponent.es.webservice.IWSGatewayService;
import com.efast.cafe.commponent.es.webservice.constant.WSConstant;
import com.efast.cafe.commponent.es.webservice.utils.W3CElementUtil;
import com.efast.cafe.commponent.log.ext.CafeLogger;
import com.efast.cafe.commponent.log.ext.CafeLoggerFactory;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.util.ConfigUtil;
import com.efast.cafe.util.HMAC;
import com.efast.cafe.util.JAXBUtil;
import com.efast.cafe.util.ProxyDelegate;
import com.efast.cafe.util.StringUtil;

/**
    * @ClassName: WSGatewayServiceImpl
    * @Description: 对外webservice统一接口
    * @author Administrator
    * @date 2018年9月18日
    *
    */
@WebService(targetNamespace="http://www.cafeauto.com",
	endpointInterface = "com.efast.cafe.commponent.es.webservice.IWSGatewayService")
@Service("wsGatewayService")
public class WSGatewayService implements IWSGatewayService{
	
	private CafeLogger logger = CafeLoggerFactory.getLogger(getClass(),ServiceTypeEnum.WEBSERVICE.name());
	
	@Autowired
	private CommonEsConfigService commonEsConfigService;
	
	    /* (非 Javadoc)
	    * 
	    * 
	    * @param message
	    * @return
	    * @see com.efast.cafe.commponent.es.webservice.WSGatewayService#doService(com.cafeauto.Message)
	    */
	    
	@Override
	public Message doService(Message message) {
		
		String bizCode = message.getBIZ_CODE();
		String messageFrom = message.getMESSAGE_FROM();
		String hmac = message.getHMAC();
		String version = StringUtil.isNullOrBlank(message.getVERSION())?"1": message.getVERSION();
		
		if(StringUtil.isNullOrBlank(bizCode)){
			throw new ServiceException("'BIZ_CODE' Can't be empty.");
		}
		
		if(StringUtil.isNullOrBlank(messageFrom)){
			throw new ServiceException("'MESSAGE_FROM' Can't be empty.");
		}
		
//		CommonEsConfig config =	commonEsConfigService.getConfig(ServiceTypeEnum.WEBSERVICE.name(), bizCode, messageFrom);
//		if(null==config){
//			throw new ServiceException("The interface config is undefined.");
//		}
//		boolean enableLog = (config.getLogs()!=null && config.getLogs().intValue()==1);
		boolean enableLog = true;
		
		String systemName = ConfigUtil.getSystemIndentifier();
		MDC.put("companyCode","");
		MDC.put("userName", message.getMESSAGE_FROM());
		logger.info("Received a cxf message from "+message.getMESSAGE_FROM());
		if(enableLog){
			LogMessage(message,"WEBSERVICE-Received-"+message.getBIZ_CODE());
		}
		
		
		
		//获取来源系统的私钥
//		String securet = config.getSec();
		String securet = null;
		
		//如果对来源系统配置了密钥，则系统需要hmac校验
		boolean isHmac = StringUtil.isNullOrBlank(securet)?false:true;
		
		if(isHmac && StringUtil.isNullOrBlank(hmac)){
			throw new ServiceException("'HMAC' Can't be empty.");
		}
		
		if(isHmac && StringUtil.isNullOrBlank(securet)){
			throw new ServiceException("Could not find the interface config in "+systemName+" Service GateWay.");
		}
		
		if(isHmac){
			String bizContent = W3CElementUtil.ElementToString(message.getBIZ_CONTENT());
			JSONObject xmlJSONObj = XML.toJSONObject(bizContent);
			JSONObject cObj = (JSONObject)xmlJSONObj.get("BIZ_CONTENT");
			String contentStr = cObj.getString("content");
			//计算HMAC值
			String hmacValid = HMAC.encryptHMAC(contentStr, securet);
			if(isHmac && !hmacValid.equals(hmac)){
				throw new ServiceException("HMAC value check failed.");
			}
			byte[] byteContent = null;
			//base64解码
			try {
				byteContent = HMAC.decryptBase64(contentStr.trim());
			} catch (Exception e1) {
				throw new ServiceException("BASE64 decode error.");
			}
			String encodeContent = new String(byteContent);
			String bizContentStart="<BIZ_CONTENT>";
			String bizContentEnd = "</BIZ_CONTENT>";
			Element el = W3CElementUtil.StringToElement(bizContentStart+encodeContent+bizContentEnd);
			message.setBIZ_CONTENT(el);
		}

		String className = WSConstant.getWebServiceClass(bizCode+version);
		
		if(StringUtil.isNullOrBlank(className)){
			throw new ServiceException("Could not find the processing class.");
		}
		try {
			Message returnMessage =	(Message)ProxyDelegate.invoke(className, "handleMessage", new Object[]{message});
			if(enableLog){
				LogMessage(returnMessage,"WEBSERVICE-Response-"+message.getBIZ_CODE());
			}
			return returnMessage;
		} catch (Exception e) {
			if(e instanceof ServiceException){
				logger.error("Business error", e);
				throw new ServiceException("Business error,"+e.getMessage());
			}else{
				logger.error("System error", e);
				throw new ServiceException("System error,"+e.getMessage());
			}
		}
	}
	
	private void LogMessage(Message message,String logKeyWord){
		try {
			String msgStr = JAXBUtil.marshalObject(message);
			logger.cacheLog(Level.INFO, msgStr, logKeyWord);
		} catch (JAXBException e) {
			logger.error("Convert message to LogMessage error", e);
		}
	}

}
